package cn.springboot.osbulkparts.service.impl;

import cn.springboot.osbulkparts.common.CommonBusinessException;
import cn.springboot.osbulkparts.common.CommonConstantEnum;
import cn.springboot.osbulkparts.common.OSLanguage;
import cn.springboot.osbulkparts.common.utils.CommonSqlUtils;
import cn.springboot.osbulkparts.dao.basedata.TMaterialRecordInfoDao;
import cn.springboot.osbulkparts.dao.system.TDictDataDao;
import cn.springboot.osbulkparts.dao.warehouse.TDeliverInfoSplitDao;
import cn.springboot.osbulkparts.entity.*;

import cn.springboot.osbulkparts.entity.formbean.GoodsListEntity;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.util.StringUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.springboot.osbulkparts.common.CommonResultInfo;
import cn.springboot.osbulkparts.common.entity.CommonEntity;
import cn.springboot.osbulkparts.common.security.entity.SecurityUserInfoEntity;
import cn.springboot.osbulkparts.config.i18n.I18nMessageBean;
import cn.springboot.osbulkparts.dao.user.MRoleInfoDao;
import cn.springboot.osbulkparts.dao.warehouse.TDeliverInfoDao;
import cn.springboot.osbulkparts.dao.warehouse.TOrderDetailInfoDao;
import cn.springboot.osbulkparts.service.GoodsListService;
import org.springframework.web.util.UriUtils;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Service
public class GoodsListServiceImpl implements GoodsListService {
    @Autowired
    private TDeliverInfoDao tDeliverInfoDao;
    @Autowired
    private TDeliverInfoSplitDao tDeliverInfoSplitDao;
    @Autowired
    private TOrderDetailInfoDao orderDetailInfoDao;
    @Autowired
    private MRoleInfoDao mroleInfoDao;
    @Autowired
    private TDictDataDao tDictDataDao;
    @Autowired
    private TMaterialRecordInfoDao materialRecordInfoDao;
    @Autowired
    private I18nMessageBean messageBean;

    @SuppressWarnings("finally")
    @Override
    public CommonResultInfo<Map<String, List<TDictDataEntity>>> initViews(String lang, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<Map<String, List<TDictDataEntity>>> result = new CommonResultInfo<Map<String, List<TDictDataEntity>>>();
        try {
            Map<String,List<TDictDataEntity>> map = new HashMap<>();
            TDictDataEntity tDictDataEntity = new TDictDataEntity();
            tDictDataEntity.setLanguageFlag(OSLanguage.localeToTableSuffix(lang));
            tDictDataEntity.setDictTypeCode("goodsStatus");
            map.put("goodsStatus",tDictDataDao.selectByPrimaryKey(tDictDataEntity));
            tDictDataEntity.setDictTypeCode("transportation");
            map.put("transportation",tDictDataDao.selectByPrimaryKey(tDictDataEntity));

            tDictDataEntity.setDictTypeCode("unit");
            map.put("unit",tDictDataDao.selectByPrimaryKey(tDictDataEntity));
            tDictDataEntity.setDictTypeCode("payment");
            map.put("payment",tDictDataDao.selectByPrimaryKey(tDictDataEntity));

            result.setResult(map);
        } catch (Exception e) {
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }
    }

    @SuppressWarnings("finally")
	@Override
    public CommonResultInfo<?> getGoodsList(TDeliverInfoEntity tDeliverInfoEntity, int pageNumber, int pageSize, Authentication auth,Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<TDeliverInfoEntity> result = new CommonResultInfo<TDeliverInfoEntity>();
        SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
        MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),tDeliverInfoEntity.getLanguageFlag());
        try {
//        	if(principal.getUserType()!=1) {
        		tDeliverInfoEntity.setDataRoleAt(roleInfoEntity.getRoleAt());
//        	}
            PageHelper.startPage(pageNumber, pageSize);
            PageInfo<TDeliverInfoEntity> pageInfo = new PageInfo<>(
                    tDeliverInfoDao.selectDeliverInfoList(tDeliverInfoEntity));
            result.setCode(ResponseEntity.ok().build().getStatusCodeValue());
            result.setResultInfo(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }
    }

    @Override
    public CommonResultInfo<?> getGoodsListSplit(TDeliverInfoSplitEntity tDeliverInfoSplitEntity, int pageNumber, int pageSize, Authentication auth, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<TDeliverInfoSplitEntity> result = new CommonResultInfo<TDeliverInfoSplitEntity>();
        SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
        MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),tDeliverInfoSplitEntity.getLanguageFlag());
        try {
//        	if(principal.getUserType()!=1) {
            tDeliverInfoSplitEntity.setDataRoleAt(roleInfoEntity.getRoleAt());
//        	}
            PageHelper.startPage(pageNumber, pageSize);
            PageInfo<TDeliverInfoSplitEntity> pageInfo = new PageInfo<>(
                    tDeliverInfoSplitDao.selectDeliverInfoListSplit(tDeliverInfoSplitEntity));
            result.setCode(ResponseEntity.ok().build().getStatusCodeValue());
            result.setResultInfo(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }
    }

    @SuppressWarnings("finally")
	@Override
    public CommonResultInfo<?> sendGoods(CommonEntity commonEntity, Authentication auth,Locale locale) {
        messageBean.setLocale(null,null,locale);
		CommonResultInfo<?> result = new CommonResultInfo<TDeliverInfoEntity>();
		result.setCode(ResponseEntity.badRequest().build().getStatusCodeValue());
		SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
		try {
			String updateUser = principal.getUserName();
			String state = "1";//已发货
			int returnInt = tDeliverInfoDao.deliverReceivingDelete(commonEntity.getIdsStr(), updateUser, state,null);
		    if (returnInt>0){
                result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
                result.setMessage(messageBean.getMessage("common.goods.send", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));
            }
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
			result.setMessage(messageBean.getMessage("common.server.error"));
			result.setException(e.getMessage().toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			return result;
		}
    }

    @Override
    public CommonResultInfo<?> deleteGoods(CommonEntity commonEntity, Authentication auth, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<?> result = new CommonResultInfo<TDeliverInfoEntity>();
        result.setCode(ResponseEntity.badRequest().build().getStatusCodeValue());
        SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
        try {
            String updateUser = principal.getUserName();
            int returnInt = tDeliverInfoDao.deliverReceivingDelete(commonEntity.getIdsStr(), updateUser, null,"1");
            if (returnInt> 0){
                tDeliverInfoSplitDao.deleteByUuid(commonEntity.getIdsStr(), updateUser,"1");
                result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
                result.setMessage(messageBean.getMessage("common.delete.success", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            return result;
        }
    }

    @Override
    public CommonResultInfo<?> receivingGoods(CommonEntity commonEntity, Authentication auth, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<?> result = new CommonResultInfo<TDeliverInfoEntity>();
        result.setCode(ResponseEntity.badRequest().build().getStatusCodeValue());
        SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
        try {
            String updateUser = principal.getUserName();
            String state = "2";//收货
            int returnInt = tDeliverInfoDao.deliverReceivingDelete(commonEntity.getIdsStr(), updateUser, state,null);
            if (returnInt>0){
                result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
                result.setMessage(messageBean.getMessage("common.goods.receive", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));

            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            return result;
        }
    }

    @Override
    public ResponseEntity<byte[]> downExcel(TDeliverInfoEntity tDeliverInfoEntity) {
        return null;
    }

    @Override
    public CommonResultInfo<?> updateGoods(TDeliverInfoEntity tDeliverInfoEntity, Authentication auth, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<?> result = new CommonResultInfo<TDeliverInfoEntity>();
        result.setCode(ResponseEntity.badRequest().build().getStatusCodeValue());
        SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
        try {
            tDeliverInfoEntity.setUpdateUser(principal.getUserName());
            int returnInt = tDeliverInfoDao.updateByPrimaryKeySelective(tDeliverInfoEntity);
            if (returnInt > 0) {
                result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
                result.setMessage(messageBean.getMessage("common.update.success", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }
    }

    @Override
    public CommonResultInfo<?> addGood(TDeliverInfoEntity tDeliverInfoEntity, Authentication auth, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<?> result = new CommonResultInfo<TDeliverInfoEntity>();
        result.setCode(ResponseEntity.badRequest().build().getStatusCodeValue());
        try {
            SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
            MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),tDeliverInfoEntity.getLanguageFlag());
            tDeliverInfoEntity.setId(CommonSqlUtils.getUUID32());
            tDeliverInfoEntity.setCreateUser(principal.getUserName());
            tDeliverInfoEntity.setIsDelete(0);
            tDeliverInfoEntity.setVersion(1);
            tDeliverInfoEntity.setDataRoleAt(roleInfoEntity.getRoleAt());
            List<TDeliverInfoEntity> list = new ArrayList<>();
            list.add(tDeliverInfoEntity);
            int returnInt = tDeliverInfoDao.insertList(list);
            if (returnInt > 0) {
                result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
                result.setMessage(messageBean.getMessage("common.add.success", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }
    }
    @Transactional
    @Override
    public CommonResultInfo<?> addGoods(TDeliverInfoEntity tDeliverInfoEntity, Authentication auth, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<?> result = new CommonResultInfo<TDeliverInfoEntity>();
        result.setCode(ResponseEntity.badRequest().build().getStatusCodeValue());
        try {
            SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
            MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),tDeliverInfoEntity.getLanguageFlag());
            //更新超发表
            TMaterialRecordInfoEntity recordParam = new TMaterialRecordInfoEntity();
            recordParam.setMaterialCode(tDeliverInfoEntity.getMaterialCode());
            recordParam.setDataRoleAt(roleInfoEntity.getRoleAt());
            BigDecimal aa =tDeliverInfoEntity.getSendAmount().subtract(tDeliverInfoEntity.getSuggestedAmount());
            if (aa.compareTo(BigDecimal.ZERO)==-1){
                recordParam.setSupperAmount(BigDecimal.ZERO);
            }else {
                recordParam.setSupperAmount(aa);
            }
            recordParam.setFactoryCode(null);
            materialRecordInfoDao.upsert(recordParam);
            //插入发货信息
            Map<String,String> map=orderDetailInfoDao.selectMaterialInfo(tDeliverInfoEntity.getMaterialCode(),roleInfoEntity.getRoleAt());
//            tDeliverInfoEntity.setId(CommonSqlUtils.getUUID32());
            tDeliverInfoEntity.setCreateUser(principal.getUserName());
//            tDeliverInfoEntity.setSupplierName(map.get("supplierNameCn"));
//            tDeliverInfoEntity.setMaterialName(map.get("materialDescCn"));
//            tDeliverInfoEntity.setUnit(map.get("materialUnit"));
            tDeliverInfoEntity.setIsDelete(0);
            tDeliverInfoEntity.setVersion(1);
            tDeliverInfoEntity.setDataRoleAt(roleInfoEntity.getRoleAt());
            List<TDeliverInfoEntity> tDeliverInfoEntityList =new ArrayList<>();
            tDeliverInfoEntityList.add(tDeliverInfoEntity);
            int returnInt = tDeliverInfoDao.insertList(tDeliverInfoEntityList);
            if (returnInt < 0) {
                throw new RuntimeException();
            }
            //根据id更新订单详情表 发货数量=发货数量+前台传过来的数量 即 tDeliverInfoEntity.getOrderDetailInfoDeliveryAmount的每一个key所对应的数量
//            String[] array=tDeliverInfoEntity.getOrderDetailInfoId();//id array
//            List<Map<String,String>> list=tDeliverInfoEntity.getOrderDetailInfoDeliveryAmount();
            List<TOrderDetailInfoEntity> resultList = tDeliverInfoEntity.getOrderDetailInfoList();
            for (TOrderDetailInfoEntity a: resultList) {
                a.setUpdateUser(principal.getUserName());
            }
            int i =orderDetailInfoDao.updateDeliveryAmountAndConfirmStatusbyIds(resultList);
            if (i<=0){
                result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
                throw new RuntimeException();
            }else {
                result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
                result.setMessage(messageBean.getMessage("common.add.success", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));
            }

//            for (int i= 0;i<list.size();i++){
//                for(int y = 0;y<array.length;y++){
//                    String value=list.get(i).get(array[y]);
//                    if("".equals(value) || value != null  ){
//                        TOrderDetailInfoEntity tOrderDetailInfoEntity = new TOrderDetailInfoEntity();
//                        tOrderDetailInfoEntity.setId(array[y]);
//                        BigDecimal a = new BigDecimal(list.get(i).get(array[y]));
//                        tOrderDetailInfoEntity.setDeliveryAmount(a);
//                        tOrderDetailInfoEntity.setUpdateUser(principal.getUserName());
//                        resultList.add(tOrderDetailInfoEntity);
//                    }
//                }
//            }



//            for (TDeliverInfoEntity tDeliverInfoEntity:tDeliverInfoEntityList) {
//                Map<String,String> map=orderDetailInfoDao.selectMaterialInfo(tDeliverInfoEntity.getMaterialCode(),roleInfoEntity.getRoleAt());
//                tDeliverInfoEntity.setId(CommonSqlUtils.getUUID32());
//                tDeliverInfoEntity.setCreateUser(principal.getUserName());
//                tDeliverInfoEntity.setSupplierName(map.get("supplierNameCn"));
//                tDeliverInfoEntity.setMaterialName(map.get("materialDescCn"));
//                tDeliverInfoEntity.setUnit(map.get("materialUnit"));
//                tDeliverInfoEntity.setIsDelete(0);
//                tDeliverInfoEntity.setVersion(1);
//                tDeliverInfoEntity.setDataRoleAt(roleInfoEntity.getRoleAt());
//                //更新超发值
//                //更新物料记录表的发货数量
//            	TMaterialRecordInfoEntity recordParam = new TMaterialRecordInfoEntity();
//            	recordParam.setMaterialCode(tDeliverInfoEntity.getMaterialCode());
//            	recordParam.setDataRoleAt(roleInfoEntity.getRoleAt());
//            	recordParam.setSupperAmount(tDeliverInfoEntity.getSendAmount().subtract(tDeliverInfoEntity.getSuggestedAmount()));
//            	recordParam.setFactoryCode(null);
//            	materialRecordInfoDao.upsert(recordParam);
//            }
//            int returnInt = tDeliverInfoDao.insertList(tDeliverInfoEntityList);
//            if (returnInt > 0) {
//                result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
//                result.setMessage(messageBean.getMessage("common.add.success", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));
//            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
            throw new RuntimeException();
        } finally {
            return result;
        }
    }

    @Override
    public CommonResultInfo<?> addGoodsSplit(List<TDeliverInfoSplitEntity> objectArray, Authentication auth, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<?> result = new CommonResultInfo<TDeliverInfoEntity>();
        result.setCode(ResponseEntity.badRequest().build().getStatusCodeValue());
        try {
            SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
            MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),null);
            //插入发货信息
            for (TDeliverInfoSplitEntity item :objectArray) {
                item.setId(CommonSqlUtils.getUUID32());
                item.setCreateUser(principal.getUserName());
                item.setIsDelete(0);
                item.setVersion(1);
                item.setDataRoleAt(roleInfoEntity.getRoleAt());
            }
            int returnInt = tDeliverInfoSplitDao.insertList(objectArray);
            if (returnInt < 0) {
                throw new RuntimeException();
            }else {
                result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
                result.setMessage(messageBean.getMessage("common.add.success", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
            throw new RuntimeException();
        } finally {
            return result;
        }
    }

    @Override
    public CommonResultInfo<Map<String,String>> selectMaterialInfo(String materialCode, Authentication auth,Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<Map<String, String>> result = new CommonResultInfo<Map<String,String>>();
        try {
            SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
            MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),null);
            Map<String,String> map=orderDetailInfoDao.selectMaterialInfo(materialCode,roleInfoEntity.getRoleAt());
            result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
            result.setResult(map);
        } catch (Exception e) {
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }

    }

    @Override
    public CommonResultInfo<?> getDeliverInfo(String id, Authentication auth, String lang, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<TDeliverInfoEntity> result = new CommonResultInfo<TDeliverInfoEntity>();
        SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
        try {
            MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),OSLanguage.localeToTableSuffix(lang));
            TDeliverInfoEntity tDeliverInfoEntity = new TDeliverInfoEntity();
            tDeliverInfoEntity.setDataRoleAt(roleInfoEntity.getRoleAt());
            tDeliverInfoEntity.setId(id);
            tDeliverInfoEntity.setLanguageFlag(OSLanguage.localeToTableSuffix(lang));
            List<TDeliverInfoEntity> resultList=tDeliverInfoDao.selectDeliverInfoList(tDeliverInfoEntity);
            if(resultList.size()>0) {
                result.setCode(ResponseEntity.ok().build().getStatusCodeValue());
                result.setResult(resultList.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }
    }

    @Override
    public CommonResultInfo<?> getInitInfoByContractNo(String contractNo, Authentication auth, String lang, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<TDeliverInfoEntity> result = new CommonResultInfo<TDeliverInfoEntity>();
        SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
        try {
            MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),OSLanguage.localeToTableSuffix(lang));
            TDeliverInfoEntity tDeliverInfoEntity = new TDeliverInfoEntity();
            tDeliverInfoEntity.setDataRoleAt(roleInfoEntity.getRoleAt());
            tDeliverInfoEntity.setContractNo(contractNo);
            tDeliverInfoEntity.setLanguageFlag(OSLanguage.localeToTableSuffix(lang));
            List<TDeliverInfoEntity> resultList=tDeliverInfoDao.getInitInfoByContractNo(tDeliverInfoEntity);

            if(resultList.size()>0) {
                result.setCode(ResponseEntity.ok().build().getStatusCodeValue());
                result.setResult(resultList.get(0));
            }else {
                result.setMessage(messageBean.getMessage("common.goods.goodsListNull"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }
    }

    @Override
    public ResponseEntity<byte[]> downloadExcel(TDeliverInfoEntity tDeliverInfoEntity,Locale locale) {
        messageBean.setLocale(null,null,locale);
        String[] title = messageBean.getMessage("file.title.goodsList").split(",");
        List<TDeliverInfoEntity> resultList = tDeliverInfoDao.selectDeliverInfoList(tDeliverInfoEntity);
        String[] titleSummary = messageBean.getMessage("file.title.goodsList.summary").split(",");
        GoodsListEntity goodsListEntity = new GoodsListEntity();
        goodsListEntity.setLanguageFlag(tDeliverInfoEntity.getLanguageFlag());
        goodsListEntity.setDepartureDateStart(tDeliverInfoEntity.getDepartureDateStart());
        goodsListEntity.setDepartureDateEnd(tDeliverInfoEntity.getDepartureDateEnd());
        List<GoodsListEntity> resultListSummary = tDeliverInfoDao.findGoodsListSummary(goodsListEntity);
        ResponseEntity<byte[]> result = educeExcel(title,resultList,locale,titleSummary,resultListSummary);
        return result;
    }
    @Transactional
    @Override
    public CommonResultInfo<?> splitGoods(String oldId, List<TDeliverInfoEntity> tDeliverInfoEntity, Authentication auth, Locale locale) {
        messageBean.setLocale(null,null,locale);
        CommonResultInfo<?> result = new CommonResultInfo<TDeliverInfoEntity>();
        result.setCode(ResponseEntity.badRequest().build().getStatusCodeValue());
        SecurityUserInfoEntity principal = (SecurityUserInfoEntity)auth.getPrincipal();
        try {
            String updateUser = principal.getUserName();
            String[] array={oldId};
            int returnInt = tDeliverInfoDao.deliverReceivingDelete(array, updateUser, null,"1");
            if (returnInt<0){
                throw new RuntimeException();
            }else {
                MRoleInfoEntity roleInfoEntity = mroleInfoDao.selectRoleInfo(principal.getRoleIdSelected(),tDeliverInfoEntity.get(0).getLanguageFlag());
                for (TDeliverInfoEntity entity:tDeliverInfoEntity) {
                    entity.setId(CommonSqlUtils.getUUID32());
                    entity.setCreateUser(principal.getUserName());
                    entity.setIsDelete(0);
                    entity.setVersion(1);
                    entity.setDataRoleAt(roleInfoEntity.getRoleAt());
                }
                int returnInsert = tDeliverInfoDao.insertList(tDeliverInfoEntity);
                if (returnInsert > 0) {
                    result.setCode(ResponseEntity.status(HttpStatus.CREATED).build().getStatusCodeValue());
                    result.setMessage(messageBean.getMessage("common.add.success", CommonConstantEnum.GOODS_DATA.getTypeName(locale)));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build().getStatusCodeValue());
            result.setMessage(messageBean.getMessage("common.server.error"));
            result.setException(e.getMessage().toString());
        } finally {
            return result;
        }
    }

    /****Private Methods****/
    /**
     *
     * @param titles 第一列名
     * @param list 向单元格插入数据
     * @return
     */
    private ResponseEntity<byte[]> educeExcel(String[] titles,List<TDeliverInfoEntity> list,Locale locale,String[] titlesSummary,List<GoodsListEntity> listSummary){
        messageBean.setLocale(null,null,locale);
        ResponseEntity<byte[]> response = null;
        //创建Excel对象
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        HSSFWorkbook workbook = new HSSFWorkbook();
        //输出Excel文件
        try {
            //创建工作表单
            HSSFSheet sheet = workbook.createSheet(messageBean.getMessage("file.name.goodsList"));
            //创建HSSFRow对象 （行）第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            row.setHeightInPoints(20);// 设备标题的高度
            //创建HSSFCell对象  （单元格）
            HSSFCell cell=null;
            //设置第一列单元格的列
            for(int i = 0; i < titles.length; i++){
                cell = row.createCell(i);//列索引从0开始
                cell.setCellValue(titles[i]);//列名1
            };
            CellStyle style =  workbook.createCellStyle();
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setFillForegroundColor(IndexedColors.RED.getIndex());
            CellStyle textStyle = workbook.createCellStyle();
            DataFormat format = workbook.createDataFormat();
            textStyle.setDataFormat(format.getFormat("@"));
            HSSFCellStyle numstyle = workbook.createCellStyle();
            numstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.000000"));
            //设置单元格的值
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i+1);
                TDeliverInfoEntity example = list.get(i);
                //合同号
                row.createCell(0).setCellValue(example.getContractNo()+"");
                //装箱日期
                row.createCell(1).setCellValue(parseDateExport(example.getPackingDate(),"yyyy/MM/dd",locale));
                //船期
                row.createCell(2).setCellValue(parseDateExport(example.getDepartureDate(),"yyyy/MM/dd",locale));
                //物料专用号
                row.createCell(3).setCellValue(example.getMaterialCode());
                //运输方式
                row.createCell(4).setCellValue( example.getDictShippingMethods() !=null ? example.getDictShippingMethods().getName() : "" );
                //提单号
                row.createCell(5).setCellValue(example.getBillNo()+"");
                //箱型号
                row.createCell(6).setCellValue(example.getContainerSize()+"");
                //集装箱号
                row.createCell(7).setCellValue(example.getContainerNo()+"");
                //供应商名称
                row.createCell(8).setCellValue(example.getSupplierName()+"");
                //物料名称
                row.createCell(9).setCellValue(example.getMaterialName()+"");
                //物料单位
                row.createCell(10).setCellValue( example.getDictUnit()!=null?example.getDictUnit().getName() : "");
                //数量
				row.createCell(11).setCellStyle(numstyle);
				row.createCell(11).setCellType(CellType.NUMERIC);
				if(example.getSendAmount() !=null) {
					row.createCell(11).setCellValue(Double.parseDouble(example.getSendAmount().toString()));
				}
				else {
					row.createCell(11).setCellValue("");
				}
                //单价
				row.createCell(12).setCellStyle(numstyle);
				row.createCell(12).setCellType(CellType.NUMERIC);
				if(example.getPrice()!=null) {
					row.createCell(12).setCellValue(Double.parseDouble(example.getPrice().toString()));
				}
				else {
					row.createCell(12).setCellValue("");
				}

                //金额
				row.createCell(13).setCellStyle(numstyle);
				row.createCell(13).setCellType(CellType.NUMERIC);
				if(example.getAmount() != null) {
					row.createCell(13).setCellValue(Double.parseDouble(example.getAmount().toString()));
				}
				else {
					row.createCell(13).setCellValue("");
				}

                //是否付款
                row.createCell(14).setCellValue(example.getDictPayment()!=null?example.getDictPayment().getName():"");
                //应付款日期
                row.createCell(15).setCellValue(parseDateExport(example.getPaymentDay(),"yyyy/MM/dd",locale));
                //实际付款日期
                row.createCell(16).setCellValue(parseDateExport(example.getPaymentDate(),"yyyy/MM/dd",locale));
                //备注
                row.createCell(17).setCellValue(StringUtil.isNotEmpty(example.getRemark())?example.getRemark():"");
                //运费及保费
				row.createCell(18).setCellStyle(numstyle);
				row.createCell(18).setCellType(CellType.NUMERIC);
//                row.createCell(18).setCellValue(StringUtil.isNotEmpty(example.getFreightPremium())?Double.parseDouble(example.getFreightPremium().toString()):null);
                if(example.getFreightPremium() != null) {
                	row.createCell(18).setCellValue(Double.parseDouble(example.getFreightPremium().toString()));
                }
                else {
                	row.createCell(18).setCellValue("");
                }


                //状态
                row.createCell(19).setCellValue(example.getDictStatus()!=null?example.getDictStatus().getName():"");
            }

            //发货的第二个sheet页

            //创建工作表单
            HSSFSheet sheetSummary = workbook.createSheet(messageBean.getMessage("file.name.goodsList.summary"));
            //创建HSSFRow对象 （行）第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow rowSummary = sheetSummary.createRow(0);
            rowSummary.setHeightInPoints(20);// 设备标题的高度
            //创建HSSFCell对象  （单元格）
            HSSFCell cellSummary=null;
            //设置第一列单元格的列
            for(int i = 0; i < titlesSummary.length; i++){
                cellSummary = rowSummary.createCell(i);//列索引从0开始
                cellSummary.setCellValue(titlesSummary[i]);//列名1
            };

            //设置单元格的值
            for (int i = 0; i < listSummary.size(); i++) {
                row = sheetSummary.createRow(i+1);
                GoodsListEntity example = listSummary.get(i);
                //物料号
                row.createCell(0).setCellValue(example.getMaterialCode()+"");
                //单耗
                row.createCell(1).setCellValue(example.getSpecificConsumption());
                //物料中文描述
                row.createCell(2).setCellValue(example.getMaterialDescCn());
                //单位
                row.createCell(3).setCellValue(example.getUnit());
                //船期
                row.createCell(4).setCellValue(example.getDepartureDate());
                //发货数量
				row.createCell(5).setCellStyle(numstyle);
				row.createCell(5).setCellType(CellType.NUMERIC);
                row.createCell(5).setCellValue(Double.parseDouble(example.getSendAmount()));

            }
            workbook.write(os);
            workbook.close();
            String filename_enc = UriUtils.encode(messageBean.getMessage("file.name.goodsList"), "UTF-8");
            response = ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .header("Access-Control-Expose-Headers","Content-Disposition")
                    .header("Content-Disposition","attachment; filename*=UTF-8''" + filename_enc+".xls")
                    .body(os.toByteArray());
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonBusinessException(e.getMessage().toString());

        }
    }
    /***
     * 日期转换
     * @param str
     * @param pattern
     * @return date
     * @throws ParseException
     */
    private String parseDateExport(String str, String pattern,Locale locale){
        messageBean.setLocale(null,null,locale);
        String returnRes = null;
        if(StringUtil.isNotEmpty(str)) {
            returnRes = str.substring(0,4)+"/"+str.substring(4,6)+"/"+str.substring(6,8);
        }
        return returnRes;
    }
}
